package com.hw.springcloud.filter;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @Classname: MyGatewayFilter
 * @Description: 自定义过滤类
 * @Date: 2021/11/12
 * @Author: HuWei
 */
@Component
@Slf4j
public class MyGatewayFilter implements GlobalFilter, Ordered {
    /**
     * 自定义过滤器
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("开始加载Gateway的自定义过滤器");
        // 获取请求参数中loginName的值
        String loginName = exchange.getRequest().getQueryParams().getFirst("loginName");
        // 对loginName进行判断过滤,如果loginName是空就设置状态并返回,否则就通过
        if(StrUtil.isBlank(loginName)){
            log.error("没有找到loginName");
            exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);
            return exchange.getResponse().setComplete();
        }
        log.info("loginName:"+loginName);
        return chain.filter(exchange);
    }

    /**
     * 表示类的加载顺序,返回值越小越先运行
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
